//
//  ViewController.swift
//  AwesomeUUIKitModule
//
//  Created by xieqiang on 04/14/2018.
//  Copyright (c) 2018 xieqiang. All rights reserved.
//

import UIKit

import AwesomeUUIKitModule

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var data: [(title: String, items: [String])] = [
        ("A", (1...10).map { "A - \($0)" }),
        ("B", (1...10).map { "B - \($0)" })
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "可拖拽排序的tableView"
        
        tableView.backgroundColor = UIColor.groupTableViewBackground
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell");
        // 1.设置拖拽代理
        self.tableView.sortable.delegate = self
        self.tableView.sortable.cellTransparent = true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let pickerVC = AUAddressPickerVC()
        pickerVC.modalPresentationStyle = .custom
        pickerVC.modalTransitionStyle = .crossDissolve
        pickerVC.pickerCompletionCallback = { (address) in
            print("\(address)")
        }
        self.present(pickerVC, animated: true, completion: nil)
    }

}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].items.count;
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return data[section].title
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 2.获取空cell
        if let emptyCell = tableView.sortable.emptyCell(indexPath: indexPath) {
            return emptyCell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath);
        cell.textLabel?.text = data[indexPath.section].items[indexPath.row];
        return cell;
    }
}

// 1.拖拽代理
extension ViewController: JWSortableTableViewDelegate {
    func jw_tableView(_ tableView: UITableView, fromRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let item = data[sourceIndexPath.section].items[sourceIndexPath.row]
        data[sourceIndexPath.section].items.remove(at: sourceIndexPath.row)
        data[destinationIndexPath.section].items.insert(item, at: destinationIndexPath.row)
    }
}


